/**
 * 
 */
package com.cwnuzj.ffms.db;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 封装JDBC操作，同时读取jdbc.properties数据源配置
 * 
 * @author jeff.zheng
 * 
 */
public final class JdbcUtil {
	private static final Log log = LogFactory.getLog(DbUtilsTemplate.class);
	private static DataSource dataSource = null;

	private JdbcUtil() {

	}

	static {
		try {
			Properties prop = new Properties();
			InputStream in = JdbcUtil.class.getResourceAsStream("jdbc.properties");
			prop.load(in);
			log.debug("读取jdbc.properties...");
//			prop.put("driverClassName", "org.apache.derby.jdbc.EmbeddedDriver");
//			prop.put("url", "jdbc:derby:D:/eclipse-rcp-indigo-win32/workspace/my-ffms/com.cwnuzj.ffms.db/ffmsdb;user=ffmsdb;password=ffmsdb");
//			prop.put("username", "ffmsdb");
//			prop.put("password", "ffmsdb");
			dataSource = BasicDataSourceFactory.createDataSource(prop);
			log.info("创建derby数据源成功");
		} catch (Exception e) {
			e.printStackTrace();
			log.error("创建derby数据源成功");
		}
	}

	public static Connection getConnection() throws SQLException {
		// return DriverManager.getConnection(url, user, password);
		try {
			return dataSource.getConnection();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new SQLException();
		}

	}

	public static DataSource getDataSource() {
		return dataSource;
	}

	public static void free(ResultSet rs, Statement st, Connection conn) {
		try {
			if (rs != null)
				rs.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (st != null)
					st.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {

				try {
					if (conn != null) {
					}
					conn.close();

				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}
